<script setup>
import {ref,reactive} from "vue";
import {useLoginStore} from "@/store";
import {storeToRefs} from "pinia";
import CodeApi from "@/api/CodeApi";
import AuthApi from "@/api/Auth"
import {ElMessage} from "element-plus"
import {useRouter} from "vue-router";
const loginStore  =useLoginStore()

const {getLoginSetting,closeLoginDialog,closeLoginLoading,openLoginLoading,setLoginUserInfo,getBeforeLoginRoutePath} = loginStore

const loginSetting = getLoginSetting()
const router = useRouter()
const countdownText = ref("点击获取验证码")
let countdownTimer = null;
const countdownTime = ref(60)
const loginComponent = ref(true)
const loginFormRule = reactive({
  account: [
    {required: true, message: "账号不能为空!", trigger: 'blue'}
  ],
  password: [{required: true, message: "密码不能为空!", trigger: 'blue'}],
  code: [{required: true, message: "验证码不能为空!", trigger: 'blue'}],
})


const loginFormRef = ref()
const registerFormRef = ref()
const loginDto = reactive({
  account: null,
  password: null
})

const registerDto = reactive({
  account: null,
  password: null,
  code: null
})

// 登录操作
const submitLogin = () => {
  loginFormRef.value.validate((valid, fields) => {
    openLoginLoading()
    if (valid) {
      AuthApi.userLogin(loginDto).then(res => {

        closeLoginLoading()
        if (!res.flag) {
          ElMessage.error(res.message)
          return
        }
        console.log("toke")
        //token存入本地
        sessionStorage.setItem("accessToken",res.data.accessToken)
        sessionStorage.setItem("refreshToken",res.data.refreshToken)
        AuthApi.getLoginUserInfo().then(res=>{
          closeLoginDialog()
          setLoginUserInfo(res.data)
          router.push(getBeforeLoginRoutePath())


        })
      })
    }
  })
}

const submitRegister = () => {
  registerFormRef.value.validate((valid ,fields)=>{
    if (valid){
      AuthApi.userRegister(registerDto).then(res=>{
        if (!res.flag) {
          ElMessage.error(res.message)
          return
        }
        ElMessage.success("注册成功")
        loginComponent.value = true

      })
    }
  })
}
const getVerifyCode = () => {
  clearInterval(countdownTimer)
  if (registerDto.account === null || registerDto.account === "") {
    ElMessage.error("请先输入邮箱账号!")
    return
  }
  CodeApi.getCode(registerDto.account).then(res=> {
    if (!res.flag) {
      ElMessage.error(res.message)
      return
    }
    ElMessage.success("验证码已发送!")
    countdownTimer = setInterval(() => {
      countdownTime.value--;
      countdownText.value = `${countdownTime.value}s重新点击获取`;
      if (countdownTime.value < 0) {
        // 倒计时结束，更新显示信息并重新开始倒计时
        countdownText.value = "点击获取验证码";
        clearInterval(countdownTimer);
        countdownTime.value = 60;
      }

    }, 1000); // 每秒更新一

  })
}


</script>

<template>
<el-dialog  v-model="loginSetting.loginDialog" :close-on-click-modal="false" @closed="console.log('close')" width="30%" style="border-radius: 8px;align-items: center">
    <h3 class="login-title">{{loginComponent?'登录':'注册'}}</h3>
    <div class="login-form" v-loading="loginSetting.loginLoading">
      <!--   登录表单-->
      <el-form :model="loginDto" :rules="loginFormRule" ref="loginFormRef" v-if="loginComponent">
        <el-form-item prop="account">
          <el-input v-model="loginDto.account" placeholder="账号" clearable
                    prefix-icon="UserFilled"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="密码" v-model="loginDto.password" show-password clearable prefix-icon="Lock"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 100%;"  @click="submitLogin">登录</el-button>
        </el-form-item>
      </el-form>
      <!--    注册表单    -->
      <el-form :model="registerDto" :rules="loginFormRule" ref="registerFormRef" v-else>
        <el-form-item prop="account">
          <el-input v-model="registerDto.account" placeholder="账号" clearable
                    prefix-icon="UserFilled"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input placeholder="密码" v-model="registerDto.password" show-password clearable prefix-icon="Lock"/>
        </el-form-item>
        <el-form-item prop="code">
          <p class="verify-code-box">
            <el-input placeholder="验证码" v-model="registerDto.code"/>
            <el-button type="primary" plain style="margin-left: 5px;font-size: 13px" :disabled="countdownTime!==60" @click="getVerifyCode">{{ countdownText }}
            </el-button>
          </p>
        </el-form-item>
        <el-form-item>
          <el-button type="primary"  style="width: 100%;" @click="submitRegister">注册</el-button>
        </el-form-item>
      </el-form>
      <p class="tip" @click="loginComponent=!loginComponent">
        {{ loginComponent ? '没有账号?去注册' : '已有账号？去登录' }}</p>
    </div>
</el-dialog>
</template>



<style scoped lang="less">


.login-title {
  height: 36px;
  line-height: 36px;
  text-align: center;
  border-radius: 8px;
}

.login-form {
  width: 70%;
  margin: 30px auto 0 auto;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.third-login {
  text-align: center;
}

.svg {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.tip {
  width: 100%;
  height: 18px;
  line-height: 18px;
  color: #409eff;
  cursor: pointer;
  font-size: 13px;
  text-align: center;
}

.verify-code-box {
  display: flex;
}
</style>